<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\index\controller;

/**
 * Description of LoginController
 *
 * @author SoChishun
 */
class LoginController {

    //put your code here
    public function indexAction() {
        return view();
    }

    public function doLoginAction() {
        $rule = [
            'username' => 'require|max:30|token',
            'password' => 'require|max:30'
        ];
        $message = [
            'username.require' => '用户名未填写',
            'username.max' => '用户名无效',
            'username.token' => '表单来源无效',
            'password.require' => '密码未填写',
            'password.max' => '密码无效',
        ];
        $request = \think\Request::instance();
        $request->only(['username', 'password', 'token']);
        $data = $request->post();
        $validate = \think\Validate::make($rule, $message);
        if (!$validate->check($data)) {
            $error = $validate->getError();
            return ['success' => false, 'message' => $error];
        }
        try {
            $user = \app\index\model\UserModel::get(['user_name' => $data['username']]);
            if (null == $user) {
                return ['success' => false, 'message' => '用户不存在'];
            }
            if ($user->password != md5($data['password'])) {
                return ['success' => false, 'message' => '密码错误'];
            }
        } catch (\think\exception\DbException $ex) {
            return ['success' => false, 'message' => $ex->getMessage()];
        }
        \think\Session::set('login',['id'=>$user->id,'user_name'=>$user->user_name]);
        return ['success' => true, 'url' => url('index/index')];
    }
    public function logoutAction(){
        \think\Session::clear();
        $response= \think\Response::create();
        redirect('login/index')->send();
    }
}
